home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / TEST.PY < prev    next >
Encoding:
Python Source  |  1999-09-03  |  15.4 KB  |  449 lines

  1. #!/bin/sh
  2. """:"
  3. exec python $0 ${1+"$@"}
  4. """
  5.  
  6. #" Waaaa
  7. ##############################################################################
  8. # Zope Public License (ZPL) Version 1.0
  9. # -------------------------------------
  10. # Copyright (c) Digital Creations.  All rights reserved.
  11. # This license has been certified as Open Source(tm).
  12. # Redistribution and use in source and binary forms, with or without
  13. # modification, are permitted provided that the following conditions are
  14. # met:
  15. # 1. Redistributions in source code must retain the above copyright
  16. #    notice, this list of conditions, and the following disclaimer.
  17. # 2. Redistributions in binary form must reproduce the above copyright
  18. #    notice, this list of conditions, and the following disclaimer in
  19. #    the documentation and/or other materials provided with the
  20. #    distribution.
  21. # 3. Digital Creations requests that attribution be given to Zope
  22. #    in any manner possible. Zope includes a "Powered by Zope"
  23. #    button that is installed by default. While it is not a license
  24. #    violation to remove this button, it is requested that the
  25. #    attribution remain. A significant investment has been put
  26. #    into Zope, and this effort will continue if the Zope community
  27. #    continues to grow. This is one way to assure that growth.
  28. # 4. All advertising materials and documentation mentioning
  29. #    features derived from or use of this software must display
  30. #    the following acknowledgement:
  31. #      "This product includes software developed by Digital Creations
  32. #      for use in the Z Object Publishing Environment
  33. #      (http://www.zope.org/)."
  34. #    In the event that the product being advertised includes an
  35. #    intact Zope distribution (with copyright and license included)
  36. #    then this clause is waived.
  37. # 5. Names associated with Zope or Digital Creations must not be used to
  38. #    endorse or promote products derived from this software without
  39. #    prior written permission from Digital Creations.
  40. # 6. Modified redistributions of any form whatsoever must retain
  41. #    the following acknowledgment:
  42. #      "This product includes software developed by Digital Creations
  43. #      for use in the Z Object Publishing Environment
  44. #      (http://www.zope.org/)."
  45. #    Intact (re-)distributions of any official Zope release do not
  46. #    require an external acknowledgement.
  47. # 7. Modifications are encouraged but must be packaged separately as
  48. #    patches to official Zope releases.  Distributions that do not
  49. #    clearly separate the patches from the original work must be clearly
  50. #    labeled as unofficial distributions.  Modifications which do not
  51. #    carry the name Zope may be packaged in any form, as long as they
  52. #    conform to all of the clauses above.
  53. # Disclaimer
  54. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  55. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  56. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  57. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  58. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  59. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  60. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  61. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  62. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  63. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  64. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  65. #   SUCH DAMAGE.
  66. # This software consists of contributions made by Digital Creations and
  67. # many individuals on behalf of Digital Creations.  Specific
  68. # attributions are listed in the accompanying credits file.
  69. ##############################################################################
  70.  
  71. __doc__='''Command-line Bobo
  72.  
  73. Usage
  74.  
  75.    bobo [options] module_path [path_info]
  76.  
  77.    where:
  78.  
  79.    module_path -- is a full path to a published module 
  80.  
  81.    path_info -- Is the information after the module name that would
  82.          normally be specified in a GET URL, including a query string.
  83.  
  84. Description
  85.  
  86.    The command-line interface to Bobo provides a handy way to test,
  87.    debug, and profile Bobo without a web server.  
  88.  
  89. Options
  90.  
  91.    -u username:password        -- Supply HTTP authorization information
  92.  
  93.    -e name=value               -- Supply environment variables.  Use a
  94.                                   seperate -e option for each variable 
  95.                                   specified.
  96.  
  97.    -p profiler_data_file       -- Run under profiler control,
  98.                                   generating the profiler 
  99.                                   data file, profiler_data_file.
  100.  
  101.    -t                          -- Compute the time required to
  102.                                   complete a request, in 
  103.                                   milliseconds.
  104.  
  105.    -r n                        -- Specify a repeat count for timing or
  106.                                   profiling.
  107.  
  108.    -d                          -- Run in debug mode.  With this
  109.                                   option, bobo will run under Python
  110.                                   debugger control.  Two useful
  111.                                   breakpoints are set.  The first is
  112.                                   at the beginning of the module
  113.                                   publishing code.  Steping through
  114.                                   this code shows how bobo finds
  115.                                   objects and obtains certain
  116.                                   meta-data.  The second breakpoint is
  117.                                   at the point just before the
  118.                                   published object is called.  To jump
  119.                                   to the second breakpoint, you must
  120.                                   enter 's' followed by a carriage
  121.                                   return to step into the module, then
  122.                                   enter a 'c' followed by a carriage
  123.                                   return to jump to the first
  124.                                   breakpoint and then another 'c'
  125.                                   followed by a carriage return to
  126.                                   jump to the point where the object
  127.                                   is called.  Finally, enter 's'
  128.                                   followed a carriage return.
  129.  
  130.    -s                             Don\'t generate any output
  131.  
  132. Examples
  133.  
  134.    For example, to debug a published object (such as a method), spam,
  135.    the following might be entered::
  136.  
  137.             bobo -d /prj/lib/python/mymod container/spam
  138.             s
  139.             c
  140.             c
  141.             s
  142.  
  143.  
  144. $Id: Test.py,v 1.35 1999/09/03 21:43:53 jim Exp $
  145. '''
  146. __version__='$Revision: 1.35 $'[11:-2]
  147.  
  148. import sys, traceback, profile, os, getopt, string
  149. from time import clock
  150. repeat_count=100
  151.  
  152. def main():
  153.     import sys, os, getopt, string
  154.     global repeat_count
  155.  
  156.     try:
  157.         optlist,args=getopt.getopt(sys.argv[1:], 'dtu:p:r:e:s')
  158.         if len(args) < 1 or len(args) > 2: raise TypeError, None
  159.         elif len(args)==1: args=args[0],'/'
  160.         path_info=args[1]
  161.     except:
  162.         sys.stderr.write(__doc__)
  163.         sys.exit(-1)
  164.  
  165.     silent=profile=u=debug=timeit=None
  166.     env={}
  167.     for opt,val in optlist:
  168.         if opt=='-d':
  169.             debug=1
  170.         if opt=='-s':
  171.             silent=1
  172.         if opt=='-t':
  173.             timeit=1
  174.         if opt=='-u':
  175.             u=val
  176.         elif opt=='-p':
  177.             profile=val
  178.         elif opt=='-r':
  179.             repeat_count=string.atoi(val)
  180.         elif opt=='-e':
  181.             opt=string.find(val,'=')
  182.             if opt <= 0: raise 'Invalid argument to -e', val
  183.             env[val[:opt]]=val[opt+1:]
  184.  
  185.     if (debug or 0)+(timeit or 0)+(profile and 1 or 0) > 1:
  186.         raise 'Invalid options', 'only one of -p, -t, and -d are allowed' 
  187.  
  188.     module=args[0]
  189.  
  190.     publish(module,path_info,u=u,p=profile,d=debug,t=timeit,e=env,
  191.             s=silent)
  192.  
  193.  
  194.  
  195. def time(function,*args,**kwargs):
  196.     repeat_range=range(repeat_count)
  197.     apply(function,args,kwargs)
  198.     t=clock()
  199.     for i in repeat_range:
  200.         apply(function,args,kwargs)
  201.     t=(clock()-t)*1000.0
  202.  
  203.     return float(t)/len(repeat_range)
  204.  
  205.  
  206.  
  207. def run(statement, *args):
  208.     import sys, profile, time
  209.  
  210.     prof = profile.Profile(time.time)
  211.     try:
  212.         prof = prof.run(statement)
  213.     except SystemExit:
  214.         pass
  215.     if args:
  216.         prof.dump_stats(args[0])
  217.     else:
  218.         return prof.print_stats()
  219.  
  220.  
  221. def publish_module(module_name,
  222.                    stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
  223.                    environ=os.environ, debug=0, request=None, response=None,
  224.                    extra={}):
  225.     must_die=0
  226.     status=200
  227.     after_list=[None]
  228.     from Response import Response
  229.     from Request import Request
  230.     from Publish import publish
  231.     try:
  232.         try:
  233.             if response is None:
  234.                 response=Response(stdout=stdout, stderr=stderr)
  235.             else:
  236.                 stdout=response.stdout
  237.             if request is None:
  238.                 request=Request(stdin, environ, response)
  239.             for k, v in extra.items(): request[k]=v
  240.             response = publish(request, module_name, after_list, debug=debug)
  241.         except SystemExit, v:
  242.             if hasattr(sys, 'exc_info'): must_die=sys.exc_info()
  243.             else: must_die = SystemExit, v, sys.exc_info()[2]
  244.             response.exception(must_die)
  245.         except ImportError, v:
  246.             if type(v) is type(()) and len(v)==3: must_die=v
  247.             elif hasattr(sys, 'exc_info'): must_die=sys.exc_info()
  248.             else: must_die = SystemExit, v, sys.exc_info()[2]
  249.             response.exception(1, v)
  250.         except:
  251.             response.exception()
  252.             status=response.getStatus()
  253.         if response:
  254.             response=str(response)
  255.         if response: stdout.write(response)
  256.  
  257.         # The module defined a post-access function, call it
  258.         if after_list[0] is not None: after_list[0]()
  259.  
  260.     finally:
  261.         if request is not None: request.close()
  262.  
  263.     if must_die:
  264.         try: raise must_die[0], must_die[1], must_die[2]
  265.         finally: must_die=None
  266.  
  267.     return status
  268.  
  269. def publish_module_pm(module_name,
  270.                       stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
  271.                       environ=os.environ, debug=0,extra={}):
  272.  
  273.     from Response import Response
  274.     from Request import Request
  275.     from Publish import publish
  276.     after_list=[None]
  277.     response=Response(stdout=stdout, stderr=stderr)
  278.     request=Request(stdin, environ, response)
  279.     for k, v in extra.items(): request[k]=v
  280.     response = publish(request, module_name, after_list, debug=debug)
  281.  
  282.  
  283.  
  284. try: from codehack import getlineno
  285. except:
  286.     def getlineno(code):
  287.         return code.co_firstlineno
  288.  
  289. defaultModule='Main'
  290. def publish(script=None,path_info='/',
  291.             u=None,p=None,d=None,t=None,e=None,s=None,pm=0,
  292.             extra=None, request_method='GET',
  293.             stdin=sys.stdin):
  294.  
  295.     profile=p
  296.     debug=d
  297.     timeit=t
  298.     silent=s
  299.     if e is None: e={}
  300.     if extra is None: extra={}
  301.  
  302.     if script is None: script=defaultModule
  303.     if script[0]=='+': script='../../lib/python/'+script[1:]
  304.  
  305.     env=e
  306.     env['SERVER_NAME']='bobo.server'
  307.     env['SERVER_PORT']='80'
  308.     env['REQUEST_METHOD']=request_method
  309.     env['REMOTE_ADDR']='204.183.226.81 '
  310.     env['REMOTE_HOST']='bobo.remote.host'
  311.     env['HTTP_USER_AGENT']='Bobo/%s' % __version__
  312.     env['HTTP_HOST']='127.0.0.1'
  313.     env['SERVER_SOFTWARE']='Bobo/%s' % __version__
  314.     env['SERVER_PROTOCOL']='HTTP/1.0 '
  315.     env['HTTP_ACCEPT']='image/gif, image/x-xbitmap, image/jpeg, */* '
  316.     env['SERVER_HOSTNAME']='bobo.server.host'
  317.     env['GATEWAY_INTERFACE']='CGI/1.1 '
  318.     env['SCRIPT_NAME']=script
  319.     p=string.split(path_info,'?')
  320.     if   len(p)==1: env['PATH_INFO'] = p[0]
  321.     elif len(p)==2: [env['PATH_INFO'], env['QUERY_STRING']]=p
  322.     else: raise TypeError, ''
  323.  
  324.     if u:
  325.         import base64
  326.         env['HTTP_AUTHORIZATION']="Basic %s" % base64.encodestring(u)
  327.  
  328.     dir,file=os.path.split(script)
  329.     cdir=os.path.join(dir,'Components')
  330.     sys.path[0:0]=[dir,cdir,os.path.join(cdir,sys.platform)]
  331.  
  332.     # We delay import to here, in case Publish is part of the
  333.     # application distribution.
  334.  
  335.     if profile:
  336.         import __main__
  337.         __main__.publish_module=publish_module
  338.         __main__.file=file
  339.         __main__.env=env
  340.         __main__.extra=extra
  341.         print profile
  342.         publish_module(file, environ=env, stdout=open('/dev/null','w'),
  343.                        extra=extra, stdin=stdin)
  344.         c=("for i in range(%s): "
  345.            "publish_module(file, environ=env, stdout=open('/dev/null','w'),"
  346.            "extra=extra)"
  347.            % repeat_count
  348.            )
  349.         if profile: run(c,profile)
  350.         else: run(c)
  351.     elif debug:
  352.         import Publish
  353.         from Publish import publish, call_object
  354.         import pdb
  355.  
  356.         class Pdb(pdb.Pdb):
  357.             def do_pub(self,arg):
  358.                 if hasattr(self,'done_pub'):
  359.                     print 'pub already done.'
  360.                 else:
  361.                     self.do_s('')
  362.                     self.do_s('')
  363.                     self.do_c('')
  364.                     self.done_pub=1
  365.             def do_ob(self,arg):
  366.                 if hasattr(self,'done_ob'):
  367.                     print 'ob already done.'
  368.                 else:
  369.                     self.do_pub('')
  370.                     self.do_c('')
  371.                     self.done_ob=1
  372.  
  373.         db=Pdb()
  374.  
  375.         def fbreak(db,meth):
  376.             try: meth=meth.im_func
  377.             except AttributeError: pass
  378.             code=meth.func_code
  379.             lineno = getlineno(code)
  380.             filename = code.co_filename
  381.             db.set_break(filename,lineno)
  382.  
  383.         fbreak(db,publish)
  384.         fbreak(db,call_object)
  385.  
  386.         dbdata={'breakpoints':(), 'env':env, 'extra': extra}
  387.         b=''
  388.         try: b=open('.bobodb','r').read()
  389.         except: pass
  390.         if b: exec b in dbdata
  391.  
  392.         for b in dbdata['breakpoints']:
  393.             if type(b) is type(()):
  394.                 apply(db.set_break,b)
  395.             else:
  396.                 fbreak(db,b)    
  397.  
  398.         db.prompt='pdb> '
  399.         # db.set_continue()
  400.  
  401.         print (
  402.         '* Type "s<cr>c<cr>" to jump to beginning of real publishing process.\n'
  403.         '* Then type c<cr> to jump to the beginning of the URL traversal\n'
  404.         '  algorithm.\n'
  405.         '* Then type c<cr> to jump to published object call.'
  406.         )
  407.         db.run('publish_module(file,environ=env,debug=1,extra=extra,'
  408.                ' stdin=stdin)',
  409.                Publish.__dict__,
  410.                {'publish_module': publish_module,
  411.                 'file':file, 'env':env, 'extra': extra, 'stdin': stdin})
  412.     elif timeit:
  413.         stdout=sys.stdout
  414.         t= time(publish_module,file,
  415.                 stdout=open('/dev/null','w'), environ=env, extra=extra)
  416.         stdout.write('%s milliseconds\n' % t)
  417.     elif pm:
  418.         stdout=sys.stdout
  419.         publish_module_pm(file, environ=env, stdout=stdout, extra=extra)
  420.         print '\n%s\n' % ('_'*60)
  421.     else:
  422.         if silent: stdout=open('/dev/null','w')
  423.         else: stdout=sys.stdout
  424.         publish_module(file, environ=env, stdout=stdout, extra=extra)
  425.         print '\n%s\n' % ('_'*60)
  426.  
  427. if __name__ == "__main__": main()
  428.